package com.fuping;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

public class TBAutoSign {

	public static void main(String[] args) {
		String BDUSS = getBDUSS();// 获取BDUSS
		String userName = getUserName(BDUSS);
		System.out.println(userName + "登录成功");
		String userId = getUserID(userName);
		String jsonStr = getTieba(userId, BDUSS);
		List<TBInfo> lt = getTieba(jsonStr);
		SimpleDateFormat ymdsdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		ymdsdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		long startTime = System.currentTimeMillis();
		StringBuffer sb = new StringBuffer();
		sb.append("<span style=\"color: rgb(255, 0, 0);\"><b>" + ymdsdf.format(new Date()) + userName
				+ "签到结果:</b></span><br><br>");
		sb.append(sdf.format(new Date(startTime)) + "开始签到：");
		sb.append("<br>*************************************************************************<br>");

		for (TBInfo tbInfo : lt) {
			String result = DoSign_Client(BDUSS, tbInfo.getTitle(), "1");
			System.out.println(result);
			sb.append(result + "<br>");
		}
		long endtTime = System.currentTimeMillis();
		sb.append("************************************************************************<br>");
		sb.append("<br>" + sdf.format(new Date(endtTime)) + "结束签到,耗时" + (endtTime - startTime) + "毫秒<br>");
		int count = 0;
		String content = sb.toString();
		while (!SendMail(content)) {

			if (count >= 5) {
				break;
			}
			SendMail(sb.toString());
			count++;
		}
	}

	public static Mail loadProperties() {

		Mail mail = null;
		InputStream in = ClassLoader
				.getSystemResourceAsStream("config.properties");
		Properties p = new Properties();
		try {
			p.load(in);
			Enumeration<Object> e = p.keys();
			if (e.hasMoreElements()) {
				mail = new Mail();
				//String key = e.nextElement().toString();
				//map.put(key, p.getProperty(key));
				mail.setMailFrom(p.getProperty("mailfrom"));
				mail.setMailPwd(p.getProperty("mailpwd"));
				mail.setMailTo(p.getProperty("mailto"));
				mail.setSmtp(p.getProperty("smtp"));
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			mail = null;
		}
		return mail;

	}
	private static boolean SendMail(String content) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		String subject = sdf.format(new Date()) + "签到结果";
		
		Mail mail = loadProperties();
		//return MailSend.send(Util.SMTP, Util.MailFrom, Util.MailTo, subject, content, Util.MailUserName, Util.MailPassWord);
		return MailSend.send(mail, subject, content);
	}

	public static Document getDoc(String url) {

		Document doc = null;
		try {
			doc = Jsoup.connect(url).header("Accept", "text/*, application/xml")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3").ignoreContentType(true)
					.timeout(10000)
					.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
					// .referrer("http://tieba.baidu.com/i/28870963/forum")
					.get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return doc;
	}

	public static Document getDoc(String url, Map<String, String> cookies) {

		Document doc = null;
		try {
			doc = Jsoup.connect(url).header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3").cookies(cookies)
					.ignoreContentType(true).timeout(10000)
					.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0")
					// .referrer("http://tieba.baidu.com/i/28870963/forum")
					.get();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return doc;
	}

	public static Document getDoc(String url, Map<String, String> data, Map<String, String> cookies) {

		Document doc = null;
		try {
			doc = Jsoup.connect(url).header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
					.header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3").cookies(cookies).data(data)
					.timeout(10000).ignoreContentType(true)
					.userAgent(
							"Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/47.0.2526.70 Mobile/13C71 Safari/601.1.46")
					.post();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return doc;
	}

	/**
	 * 读取BDUSS
	 * 
	 * @return
	 */
	public static String getBDUSS() {
		
		String bduss = null;
		InputStream in = ClassLoader
				.getSystemResourceAsStream("config.properties");
		Properties p = new Properties();
		try {
			p.load(in);
			Enumeration<Object> e = p.keys();
			if (e.hasMoreElements()) {
				bduss = p.getProperty("bduss");
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			
		}
		return bduss;
	}

	/**
	 * 根据BDUSS获取用户的昵称
	 * 
	 * @param BDUSS
	 * @return
	 */
	public static String getUserName(String BDUSS) {
		String url = "http://wapp.baidu.com/";
		String userName = null;
		Map<String, String> cookies = new HashMap<String, String>();
		String BAIDUID = MD5.stringMD5(System.currentTimeMillis() / 1000L + "");
		cookies.put("BDUSS", BDUSS);
		cookies.put("BAIDUID", BAIDUID);
		Document doc = getDoc(url, cookies);
		if (doc != null) {
			try {
				userName = URLDecoder.decode(doc.select("div.b").select("a").attr("href").split("un=")[1], "utf-8");
			} catch (UnsupportedEncodingException e) {

			}
		}
		return userName;
	}

	/**
	 * 获取userid
	 * 
	 * @param userName
	 * @return
	 */
	public static String getUserID(String userName) {
		String userId = null;
		String url = null;
		try {
			url = "http://tieba.baidu.com/home/get/panel?ie=utf-8&un=" + URLEncoder.encode(userName, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Document doc = getDoc(url);
		if (doc != null) {
			String jsonStr = doc.text();
			try {
				
				JSONObject json = new JSONObject(jsonStr);
				userId = json.getJSONObject("data").get("id").toString();
			} catch (JSONException e) {
				userId = "172363399";
			}
		}
		return userId;
	}

	public static String getTieba(String userId, String BDUSS) {
		String result = null;
		String url = "http://c.tieba.baidu.com/c/f/forum/like";
		int pn = 0;// 默认一页就够了
		Map<String, String> data = new TreeMap<String, String>();
		data.put("_client_id", "wappc_" + System.currentTimeMillis() / 1000L + "_258");
		data.put("_client_type", 2 + "");
		data.put("_client_version", "6.5.8");
		data.put("_phone_imei", "357143042411618");
		data.put("from", "baidu_appstore");
		data.put("is_guest", "1");
		data.put("model", "H60-L01");
		data.put("page_no", pn + "");
		data.put("page_size", "200");
		data.put("timestamp", System.currentTimeMillis() / 1000L + "903");
		data.put("uid", userId);
		StringBuffer sb = new StringBuffer();
		Iterator<String> it = data.keySet().iterator();
		while (it.hasNext()) {
			// it.next()得到的是key，tm.get(key)得到obj
			String key = it.next();
			Object value = data.get(key);
			sb.append(key);
			sb.append("=");
			sb.append(value);
		}
		String sign_str = sb.toString();
		String sign = MD5.stringMD5(sign_str + "tiebaclient!!!");
		data.put("sign", sign);
		Map<String, String> cookies = new HashMap<String, String>();
		cookies.put("BDUSS", BDUSS);
		Document doc = getDoc(url, data, cookies);
		if (doc != null) {
			result = doc.text();
		}
		return result;
	}

	public static List<TBInfo> getTieba(String jsonStr) {
		List<TBInfo> lt = new ArrayList<TBInfo>();
		TBInfo tbInfo;
		try {
			JSONObject json = new JSONObject(jsonStr);
			JSONObject forum_list = json.getJSONObject("forum_list");
			JSONArray js_non = forum_list.getJSONArray("non-gconforum");
			JSONArray js = forum_list.getJSONArray("gconforum");
			for (int i = 0; i < js_non.length(); i++) {
				tbInfo = new TBInfo();
				tbInfo.setTitle(js_non.getJSONObject(i).getString("name"));
				tbInfo.setId(js_non.getJSONObject(i).getString("id"));
				lt.add(tbInfo);
			}
			for (int i = 0; i < js.length(); i++) {
				tbInfo = new TBInfo();
				tbInfo.setTitle(js.getJSONObject(i).getString("name"));
				tbInfo.setId(js.getJSONObject(i).getString("id"));
				lt.add(tbInfo);
			}
		} catch (JSONException e) {

		}

		return lt;
	}

	/*
	 * 获取TBS
	 */
	public static String getTBS(String BDUSS) {
		String tbs = null;
		String url = "http://tieba.baidu.com/dc/common/tbs";
		Map<String, String> cookies = new HashMap<String, String>();
		cookies.put("BDUSS", BDUSS);
		Document doc = getDoc(url, cookies);
		if (doc != null) {
			try {
				JSONObject json = new JSONObject(doc.text());
				tbs = json.getString("tbs");
			} catch (JSONException e) {
				// TODO Auto-generated catch block

			}
		}
		return tbs;
	}

	/**
	 * 客户端签到 经验+6 连续+8
	 * 
	 * @param BDUSS
	 * @param kw
	 *            贴吧名称
	 * @param fid
	 *            1或0
	 */
	public static String DoSign_Client(String BDUSS, String kw, String fid) {

		String url = "http://c.tieba.baidu.com/c/c/forum/sign";
		Map<String, String> cookies = new HashMap<String, String>();
		cookies.put("BDUSS", BDUSS);
		Map<String, String> data = new TreeMap<String, String>();
		data.put("BDUSS", BDUSS);
		data.put("_client_id", "03-00-DA-59-05-00-72-96-06-00-01-00-04-00-4C-43-01-00-34-F4-02-00-BC-25-09-00-4E-36");
		data.put("_client_type", "4");
		data.put("_client_version", "1.2.1.17");
		data.put("_phone_imei", "540b43b59d21b7a4824e1fd31b08e9a6");
		data.put("fid", fid);
		data.put("kw", kw);
		data.put("net_type", "3");
		data.put("tbs", getTBS(BDUSS));
		StringBuffer sb = new StringBuffer();
		Iterator<String> it = data.keySet().iterator();
		while (it.hasNext()) {
			// it.next()得到的是key，tm.get(key)得到obj
			String key = it.next();
			Object value = data.get(key);
			sb.append(key);
			sb.append("=");
			sb.append(value);
		}
		String sign_str = sb.toString();
		String sign = MD5.stringMD5(sign_str + "tiebaclient!!!");
		data.put("sign", sign);
		Document doc = getDoc(url, data, cookies);
		String result = null;
		if (doc != null) {
			try {
				JSONObject json = new JSONObject(doc.text());
				result = kw + "--------->" + Result.getName(Integer.parseInt(json.get("error_code").toString()));
			} catch (JSONException e) {
			}

		}
		return result;
	}

}
